package com.csproj.system.resource;

import com.codahale.metrics.annotation.Timed;

import com.csproj.siiat.base.common.dto.BaseDTO;
import com.csproj.siiat.base.common.menu.SysMenuDTO;
import com.csproj.siiat.base.common.menu.service.SysMenuService;
import com.csproj.siiat.base.common.repository.PageableTools;
import com.csproj.siiat.security.SecurityUtils;
import com.csproj.system.domain.UserInfo;
import com.csproj.system.repository.UserInfoRepository;
import com.csproj.system.service.SysLogsService;
import com.csproj.system.service.UserInfoService;
import com.csproj.system.service.dto.UserInfoDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * REST controller for managing UserInfo.
 */
@RestController
@RequestMapping("/api/siiat/v1")
public class UserInfoResource {

    private final Logger log = LoggerFactory.getLogger(UserInfoResource.class);

    private static final String ENTITY_NAME = "userInfo";

    private final UserInfoService userInfoService;
    private final UserInfoRepository userInfoRepository;
    private final SysMenuService sysMenuService;
    private final SysLogsService sysLogsService;


    public UserInfoResource(UserInfoService userInfoService, UserInfoRepository userInfoRepository, SysMenuService sysMenuService, SysLogsService sysLogsService) {
        this.userInfoService = userInfoService;
        this.userInfoRepository = userInfoRepository;
        this.sysMenuService = sysMenuService;
        this.sysLogsService = sysLogsService;
    }

    /**
     * POST  /user-infos : 新增用户信息
     *
     * @param userInfoDTO the userInfoDTO to create
     * @return BaseDTO
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/userInfos")
    @Timed
    public BaseDTO createUserInfo(HttpServletRequest request, @RequestBody UserInfoDTO userInfoDTO) throws URISyntaxException {


        if( userInfoRepository.findByPhone(userInfoDTO.getPhone())!=null) {
            return BaseDTO.createBaseDTO().setSuccess(false).setMessage("user_phone_duplicate");
        }
        if( userInfoRepository.findByAccount(userInfoDTO.getAccount())!=null) {
            return BaseDTO.createBaseDTO().setSuccess(false).setMessage("user_account_duplicate");
        }
        UserInfo curretnUser = this.userInfoService.getCurrentUser();
        this.sysLogsService.saveForGet("", curretnUser.getAccount()+":user_create_user","");

        UserInfoDTO result =  userInfoService.save(userInfoDTO);
        return BaseDTO.createBaseDTO(result);
    }

    /**
     * PUT  /user-infos : 修改用户信息
     *
     * @param userInfoDTO the userInfoDTO to update
     * @return BaseDTO
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/userInfos/{id}")
    @Timed
    public BaseDTO updateUserInfo(HttpServletRequest request,@RequestBody(required = false) UserInfoDTO userInfoDTO,@PathVariable String id) throws URISyntaxException {
        log.debug("REST request to update UserInfo : {}", userInfoDTO);
        userInfoDTO.setId(id);
        if (userInfoDTO.getId() == null) {
            return createUserInfo(request,userInfoDTO);
        }
        UserInfo userInfo =  userInfoRepository.findByPhone(userInfoDTO.getPhone());
        if( userInfo!=null && !userInfo.getId().equals(id)) {
            return BaseDTO.createBaseDTO().setSuccess(false).setMessage("user_phone_duplicate");

        }
        UserInfo userInfoaccont = userInfoRepository.findByAccount(userInfoDTO.getAccount());
        if(userInfoaccont!=null && !userInfoaccont.getId().equals(id))  {
            return BaseDTO.createBaseDTO().setSuccess(false).setMessage("user_account_duplicate");
        }

        UserInfo curretnUser = this.userInfoService.getCurrentUser();
        this.sysLogsService.saveForGet("", curretnUser.getAccount()+":user_update_user","");
        UserInfoDTO result = userInfoService.save(userInfoDTO);
        return BaseDTO.createBaseDTO(result).setMessage("save_success");
    }



    /**
     * GET  获取用户列表 (分页)
     * @param pageNumber	当前页数
     * @return BaseDTO		返回值
     */
    @GetMapping("/userInfos")
    @Timed
    public BaseDTO getAllUserInfos(@RequestParam(value="pageNumber",required=false) Integer pageNumber,
                                   @RequestParam(value="pageSize",required = false) Integer pageSize,
                                   @RequestParam(value="keyWord",required=false) String keyWord,
                                   @RequestParam(value="roleId",required=false) String roleId,
                                   @RequestParam(value="siteId",required=false) String siteId
                                   ) {
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getAccount()+":user_get_user_list","");

        log.debug("REST request to get all UserInfos");
        Pageable pageable = PageableTools.basicPage(pageNumber,pageSize);
        if (pageNumber == null || pageNumber == 0) {
            return BaseDTO.createBaseDTOByFieldList(userInfoService.findAll());
        }
        Map<String, Object> queryParams = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(keyWord)) {
            queryParams.put("keyWord",keyWord);
        }
        if (StringUtils.isNotBlank(roleId)) {
            queryParams.put("roleId",roleId);
        }
        if (StringUtils.isNotBlank(siteId)) {
            queryParams.put("siteId",siteId);
        }

        return userInfoService.findPageList(queryParams,pageable);
    }

    /**
     * GET  /users : 获取用户信息(不分页)
     * @return BaseDTO
     */
    @GetMapping("/allUserInfos")
    @Timed
    public BaseDTO getAllUserInfoList() {
        return BaseDTO.createBaseDTOByFieldList(userInfoService.findAll());
    }

    /**
     * GET 获取用户一个对象
     * @param id	用户id
     * @return BaseDTO
     */
    @GetMapping("/userInfos/{id}")
    @Timed
    public BaseDTO getUserInfo(@PathVariable String id) {
        log.debug("REST request to get UserInfo : {}", id);
        UserInfoDTO userInfoDTO = userInfoService.findOne(id);
        return BaseDTO.createBaseDTO(userInfoDTO);
    }

    /**
     * DELETE  删除用户
     * @param	id	 用户id
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/userInfos/{id}")
    @Timed
    public BaseDTO deleteUserInfo(@PathVariable String id) {
        log.debug("REST request to delete UserInfo : {}", id);
        sysLogsService.saveForDelete(id,"DELETE_USER",ENTITY_NAME);
        return userInfoService.delete(id);
    }

    /**
     * 批量删除用户
     * @param ids   用户的ids
     * @return
     */
    @DeleteMapping("/userInfos/deleteUserInfos")
    @Timed
    public BaseDTO deleteUserInfos (@RequestBody(required=false) String[] ids){
        userInfoService.deleteUserInfos(ids);
        return BaseDTO.createBaseDTO();
    }

    /**
     * PUT  /userInfos/updateUserInfoStatus/{id} : 修改用户使用状态
     *
     * @param userInfoDTO
     * @param id
     * @return BaseDTO
     * @throws URISyntaxException
     */
    @PutMapping("/userInfos/updateUserInfoStatus/{id}")
    @Timed
    public BaseDTO updateUserInfoStatus(HttpServletRequest request,@RequestBody(required = false) UserInfoDTO userInfoDTO,@PathVariable String id) throws URISyntaxException {
        log.debug("REST request to update UserInfo isUse : {}", userInfoDTO);
        userInfoDTO.setId(id);
        if (userInfoDTO.getId() == null) {
            return createUserInfo(request,userInfoDTO);
        }
        UserInfoDTO result = userInfoService.updateUserInfoStatus(userInfoDTO);
        return BaseDTO.createBaseDTO(result).setMessage("save_success");
    }

    /**
     * 验证短信码并修改密码
     *
     * @param userInfoDTO
     * @return
     */
    @PostMapping("/verificationCode/verificate")
    public BaseDTO verificate(@RequestBody UserInfoDTO userInfoDTO) {
        return userInfoService.verificate(userInfoDTO);
    }

    /**
     * 修改密码
     *
     * @param userInfoDTO
     * @return
     */
    @PostMapping("/updatePassword")
    public BaseDTO updatePassword(@RequestBody UserInfoDTO userInfoDTO) {
        return userInfoService.updatePassword(userInfoDTO);
    }

    /**
     * 修改密码
     *
     * @param userInfoDTO
     * @return
     */
    @PostMapping("/setPassword")
    public BaseDTO setPassword(@RequestBody UserInfoDTO userInfoDTO) {
        return userInfoService.setPassword(userInfoDTO);
    }





    /**
     * 为新增用户添加bc角色
     * @param userInfoIds
     * @return
     */
    @GetMapping("/userInfos/changeRoleInfoById")
    @Timed
    public BaseDTO changeRoleInfoById(@RequestParam String userInfoIds){
        BaseDTO baseDTO = userInfoService.changeRoleInfoById(userInfoIds);
        return baseDTO;
    }

    /**
     * 获取当前用户 getAll接口
     */
    @GetMapping("/getall")
    @Timed
    public BaseDTO getAll(){
        SysMenuDTO sysMenuDTO = sysMenuService.getAll();
        return BaseDTO.createBaseDTO(sysMenuDTO);
    }

    @GetMapping("/getCurrentLoginInformations")
    @Timed
    public BaseDTO getCurrentLoginInformations(){
        String userId =SecurityUtils.getCurrentUserId();
        UserInfoDTO userInfo;
        if(StringUtils.isNotBlank(userId)){
            userInfo = userInfoService.findOne(userId);
            userInfo.setPassword("");
            userInfo.setOldPass("");
        }
        else
        {
            userInfo = null;
        }
        return BaseDTO.createBaseDTO(userInfo);
    }

    /**
     *  批量导入
     */
    @PostMapping("/userinfos/batchImport")
    @Timed
    public BaseDTO batchImport(MultipartFile file){
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getAccount()+":user_upload_batch_import","");
        return  userInfoService.batchImport(file) ;
    }
}
